package com.yricky.memoria.utils

import android.os.Handler
import android.os.Looper
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.StringRes
import androidx.compose.ui.graphics.Color
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.yricky.memoria.data.WorkSpaceModel
import java.util.concurrent.PriorityBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

/**
 * @author Yricky
 * @date 2021/11/21
 */
object UID{
    fun subject():String = genUID("sub_")
    fun subjectTag():String = genUID("subT")
    fun section():String = genUID("sec_")
    fun sectionTag():String = genUID("secT")
    fun custom(t:String) = genUID(t)

    private fun genUID(type:String):String{
        return "$type${String.format("%016x%016x%016x",System.currentTimeMillis(), rLong, rLong)}"
    }
    private val rLong get() = Math.random().toRawBits()
}

object RStr{
    fun from(@StringRes resId:Int):String{
        return globalContext.getString(resId)
    }

    /**
     * 表示这段文本需要写在R.string里，但是现在还没有写在里面。
     */
    @Deprecated("Use RStr.from")
    fun stub(str:String):String{
        return str
    }
}

object RColor{
    fun compose(@ColorRes resId:Int):Color{
        return Color(globalContext.getColor(resId))
    }

    @ColorInt
    fun integer(@ColorRes resId:Int):Int{
        return globalContext.getColor(resId)
    }
}

object Executor{
    private class UrgencyRunnable(val timeoutMillis:Int, private val r:Runnable):Runnable{
        val birth = System.currentTimeMillis()
        override fun run() {
            if(System.currentTimeMillis() - birth < timeoutMillis)
                r.run()
        }
    }
    private val tpe: ThreadPoolExecutor by lazy {
        ThreadPoolExecutor(
            1,
            8,
            100L,
            TimeUnit.MILLISECONDS,
            PriorityBlockingQueue(8) { r1, r2 ->
                if(r1 is UrgencyRunnable && r2 is UrgencyRunnable){
                    (r2.birth - r1.birth).toInt()
                }else{
                    r1.hashCode()-r2.hashCode()
                }
            })
    }


    fun execUrgency(runnable: Runnable){
        tpe.execute(UrgencyRunnable(5000,runnable))
    }

    fun exec(runnable: Runnable){
        tpe.execute(runnable)
    }
}
val mainThreadHandler:Handler by lazy{
    Handler(Looper.getMainLooper())
}

val ws:WorkSpaceModel by lazy{
    WorkSpaceModel(globalContext.getExternalFilesDir("ws")!!)
}

val gson: Gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()

